package top.itaso.app.ui.progressbar;

import android.app.Application;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.OnLifecycleEvent;

import top.itaso.app.MyApplication;
import top.itaso.lib.alog.ALog;

public class ProgressBarViewModel extends AndroidViewModel implements LifecycleObserver {
    private static final String TAG = "ProgressBarViewModel";
    private final static int MSG_DOWNLOAD = 1;

    private MutableLiveData<DownloadFileBean> _downloadFile;

    private final String mFileSaveRootPath = getApplication().getExternalCacheDir().getAbsolutePath();
    /**
     * 模拟文件下载的事件分发，即 Http 发起 request 动作之后的事情，如：
     * IO存储、UI刷新等
     */
    private Handler mHandlerUI = new Handler(Looper.getMainLooper()) {

        private final long downloadSize = 1024 * 1024;//1MB

        @Override
        public void dispatchMessage(@NonNull Message msg) {
            super.dispatchMessage(msg);
            ALog.vTag(TAG, "msg.what:%s", msg.what);
            DownloadFileBean downloadFileBean = (DownloadFileBean) msg.obj;
            if (downloadFileBean.getFileState() != DownloadFileBean.EFileState.STARTING) {
                //非 STARTING 状态时，即非正常下载状态，则立即更新数据状态，模拟阻断IO存储并
                _downloadFile.setValue(downloadFileBean);
                return;
            }

            downloadFileBean.setDownloadSpeed(downloadSize);//设置下载速度1MB/s

            long unDownload = downloadFileBean.getFileSize() - downloadFileBean.getDownloadSize();
            if (unDownload <= 0) {
                onInterruptDownload(DownloadFileBean.EFileState.FINISH);//下载完成
                _downloadFile.setValue(downloadFileBean);
                return;
            }
            if (unDownload / downloadSize <= 0) {//最后一次读流
                downloadFileBean.setDownloadSize(downloadFileBean.getDownloadSize() + unDownload);
            } else {
                downloadFileBean.setDownloadSize(downloadFileBean.getDownloadSize() + downloadSize);//模拟每次读取 1MB 文件流
            }
            _downloadFile.setValue(downloadFileBean);

            Message progressMsg = Message.obtain();
            progressMsg.what = MSG_DOWNLOAD;
            progressMsg.obj = downloadFileBean;
            sendMessageDelayed(progressMsg, 1000);
        }
    };

    public ProgressBarViewModel(Application application) {
        super(application);
        _downloadFile = new MutableLiveData<>();
    }

    public LiveData<DownloadFileBean> observeDownloadFile() {
        return _downloadFile;
    }


    /**
     * 开始模拟下载文件
     */
    public void startDownload() {
        DownloadFileBean downloadFileBean = _downloadFile.getValue();
        if (downloadFileBean != null
                && downloadFileBean.getFileState() == DownloadFileBean.EFileState.STARTING) {
            onInterruptDownload(DownloadFileBean.EFileState.PAUSING);
            return;
        }


        if (downloadFileBean == null) {
            downloadFileBean = new DownloadFileBean();
            downloadFileBean.setSavePath(mFileSaveRootPath);
            downloadFileBean.setFileSize(100 * 1024 * 1024);//100MB
            downloadFileBean.setDownloadSize(0);
            downloadFileBean.setDownloadSpeed(0);
            downloadFileBean.setFileDesc("这是一个文件下载进度条示例");
        } else {
            if (downloadFileBean.getHasDownloadPercentValue() >= 100) {
                downloadFileBean.setDownloadSpeed(0);
                downloadFileBean.setDownloadSize(0);
            }
        }
        downloadFileBean.setFileState(DownloadFileBean.EFileState.STARTING);

        Message downloadMsg = Message.obtain();
        downloadMsg.what = 1;
        downloadMsg.obj = downloadFileBean;
        mHandlerUI.sendMessage(downloadMsg);
    }

    /**
     * 中断模拟下载
     */
    public void onInterruptDownload(DownloadFileBean.EFileState fileState) {
        if (mHandlerUI != null) {
            DownloadFileBean downloadFileBean = _downloadFile.getValue();
            if (downloadFileBean == null) {
                return;
            }
            downloadFileBean.setFileState(fileState);

            Message downloadMsg = Message.obtain();
            downloadMsg.what = 1;
            downloadMsg.obj = downloadFileBean;
            mHandlerUI.sendMessage(downloadMsg);
//            mHandlerUI.removeCallbacksAndMessages(null);
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy() {
        ALog.vTag(TAG, "......");
        if (mHandlerUI != null) {
            mHandlerUI.removeCallbacksAndMessages(null);
        }
    }
}